<?php

/**
 * This is the model class for table "setting".
 *
 * The followings are the available columns in table 'setting':
 * @property integer $id
 * @property string $key
 * @property string $settingValue
 * @property string $settingName
 * @property string $settingDescription
 * @property string $type
 * @property string $value
 * @property string $name
 * @property string $description
 * @property array $notSavedDropDownModels
 */
class Setting extends CActiveRecord
{
    protected static $types=array(
        'text',
        'int',
        'img',
        'dropDown',
    );
    protected $value, $dropDownLang, $__dropDownModels, $__dropDownArray;
    private $__notSavedDropDownModels=array();

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'setting';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('key, settingValue', 'required'),
            array('key, type', 'length', 'max'=>128),
            array('settingName', 'length', 'max'=>256),
            array('settingDescription', 'length', 'max'=>1024),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, key, settingValue, settingName, settingDescription, type', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            //'image'=>array(self::BELONGS_TO, 'File', 'imageId'),
        );
    }

    public function behaviors(){
        return array(
            'lang'=>array(
                'class'=>'MultiLanguageBehavior',
                //'imagePath'=>'upload/images/posts',
                //'imageField'=>'image',
            ),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => Yii::t('main','id'),
            'key' => Yii::t('settings','name'),
            'name' => Yii::t('main','name'),
            'value' => Yii::t('main','value'),
            'type'  => Yii::t('settings','type'),
            'description' => Yii::t('main','description'),
            'properties' => Yii::t('main','properties'),
            'dropDownValueKey'=>Yii::t('settings','key'),
            'dropDownValueName'=>Yii::t('settings','name'),
        );
    }

    /* Getters */

    public static function getConfig($configName)
    {
        $result=self::model()->findByAttributes(array('key'=>$configName));

        $value=$result->value;

        return $value ? $value : $result->settingValue;
    }

    public function getValue()
    {
        if($this->type=='dropDown'){
            $languages=Language::model()->all;
            foreach($languages as $lang){
                if($this->settingValue==$lang->code) return $lang->name;
            }
        }elseif($this->type=='img'){
            return '<img class="setting-image" src="'.Yii::app()->file->getImageUrl($this->settingValue).'" />';
        }

        $result=$this->lang->translate('settingValue');
        return $result ? $result : $this->settingValue;
    }

    public function getName()
    {
        $result=$this->lang->translate('settingName');
        return $result ? $result : $this->settingName;
    }

    public function getDescription()
    {
        $result=$this->lang->translate('settingDescription');
        return $result ? $result : $this->settingDescription;
    }

    public function getDropDownValueKey()
    {
        return $this->settingValue;
    }

    public function getDropDownValueName()
    {
        return $this->settingValue;
    }

    public function getDropDownModels()
    {
        if($this->__dropDownModels===null){
            $this->__dropDownModels=SettingDropDown::model()->findAllByAttributes(array(
                'settingId'=>$this->id,
            ));
        }

        return $this->__dropDownModels;
    }

    public function getDropDownArray()
    {
        if($this->__dropDownArray===null){
            $this->__dropDownArray=array();

            foreach($this->dropDownModels as $dropDownModel){
                foreach($dropDownModel->multiLangModels as $multiLangModel){
                    $langCode=$multiLangModel->lang;
                    $this->__dropDownArray[$dropDownModel->name][$langCode]=$multiLangModel->value;
                }
            }
        }

        return $this->__dropDownArray;
    }

    public function getDropDown()
    {
        $dropDown=array();
        foreach($this->dropDownArray as $num=>$array){
            $dropDown[$num]=$array[Yii::app()->language];
        }
        return $dropDown;
    }

    public function getDropDownLang()
    {
        $languages=array();

        foreach(Language::model()->all as $lang){
            $languages[$lang->code]=$lang->name;
        }

        return $languages;
    }

    public function getDropDownType()
    {
        $types=array();

        foreach(self::$types as $type){
            $types[$type]=Yii::t('settings',$type);
        }

        return $types;
    }

    public function getNotSavedDropDownModels()
    {
        return $this->__notSavedDropDownModels;
    }

    public function getDropDownValueKeys()
    {
        return $this->__dropDownValueKeys;
    }

    /* END Getters */



    /* Setters */

    public function setType($type)
    {
        $this->type=$type;
    }

    public function setValue($value)
    {
        if($this->type=='img'){
            if($value=Yii::app()->file->saveImage($this,'value')) $this->settingValue=$value;
        }elseif($this->type=='int' || $this->type=='dropDown'){
            $this->settingValue=$value;
        }elseif(is_array($value)){
            $this->settingValue=$this->lang->setMultiLangValues('settingValue',$this,$value);
        }
    }

    public function setName($name)
    {
        $this->settingName=$this->lang->setMultiLangValues('settingName',$this,$name);
    }

    public function setDescription($description)
    {
        $this->settingDescription=$this->lang->setMultiLangValues('settingDescription',$this,$description);
    }

    public function setDropDownValueKey($keys)
    {
        foreach($keys as $key){
            if($key && !$this->settingValue){
                $this->settingValue=$key;
                break;
            }
        }

        foreach($keys as $num=>$key){
            if(is_string($key) && strlen($key)>0){
                $attributes=array(
                    'settingId'=>$this->id,
                    'name'=>$key,
                );

                $dropDownModel=SettingDropDown::model()->findByAttributes($attributes);

                if($dropDownModel===null){
                    $dropDownModel=new SettingDropDown();
                    $dropDownModel->attributes=$attributes;
                }

                $this->__notSavedDropDownModels[$num]=$dropDownModel;
            }
        }
    }

    public function setDropDownValueName($names)
    {
        if($this->notSavedDropDownModels){
            $langNames=array();

            foreach($names as $code=>$words){
                foreach($words as $num=>$word){
                    if($word) $langNames[$num][$code]=$word;
                }
            }

            foreach($this->notSavedDropDownModels as $num=>$model){
                if(isset($langNames[$num])) $model->lang->setMultiLangValues('name',$model,$langNames[$num]);
            }
        }
    }

    public function setNotSavedDropDownModels($models)
    {
        if(!is_array($models)) $models=array($models);

        foreach($models as $dropDownModel){
            if(is_object($dropDownModel)) $this->__notSavedDropDownModels[]=$dropDownModel;
        }
    }

    /* END Setters */

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('key',$this->key,true);
        $criteria->compare('settingValue',$this->settingValue,true);
        $criteria->compare('settingName',$this->settingName,true);
        $criteria->compare('settingDescription',$this->settingDescription,true);
        $criteria->compare('type',$this->type,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    public function afterSave()
    {
        if(!$this->lang->afterSave()) return false;
        if($this->notSavedDropDownModels){
            $result=$this->lang->afterSaveFunction($this->notSavedDropDownModels,$this->id,'settingId');
            if(!$result) return false;
        }
        return parent::afterSave();
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Setting the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}
